<template>
  <div id="cont">
    <div>
      <Form
        ref="detail"
        :rules="formValidate"
        :label-width="140"
        :model="detail"
        class="tab-detail"
      >
        <Row
          wrap
          style="align-items: flex-start;margin-bottom:5px;display:block"
        >
          <Col :lg="8" :xs="24">
            <FormItem prop="image" :label-width="50">
              <div class="detail-image-box">
                <viewer :images="detail.image">
                  <img
                    style="max-width:100%;max-height:230px"
                    :src="detail.image"
                    alt=""
                    readonly
                  />
                </viewer>
              </div>
            </FormItem>
          </Col>
          <Col :lg="8" :xs="24">
            <FormItem label="编号" prop="sn">
              <Input v-model="detail.sn" readonly />
            </FormItem>
            <FormItem label="型号" prop="model">
              <Input v-model="detail.model" readonly />
            </FormItem>
            <FormItem label="供应商" prop="supplier">
              <Input v-model="detail.supplier" readonly />
            </FormItem>
            <FormItem label="循环圆直径(mm)" prop="diameter">
              <Input
                type="number"
                v-model.number="detail.diameter"
                style="width:100%"
                :max="5000"
                :min="0"
                readonly
              />
            </FormItem>

            <FormItem label="启动变矩比" prop="initialTorqueRatio">
              <Input
                type="number"
                v-model.number="detail.initialTorqueRatio"
                style="width:100%"
                :max="100"
                :min="0"
                readonly
              />
            </FormItem>
          </Col>
          <Col :lg="8" :xs="24">
            <FormItem label="特性类型" prop="type">
              <Select v-model="detail.type" disabled>
                <Option value="λ曲线">λ曲线</Option>
                <Option value="Cf曲线">Cf曲线</Option>
                <Option value="K曲线">K曲线</Option>
                <Option value="Mbg曲线">Mbg曲线</Option>
              </Select>
            </FormItem>
            <FormItem label="泵轮转动惯量(kg*m^2)" prop="pumpInertia">
              <Input
                type="number"
                v-model.number="detail.pumpInertia"
                style="width:100%"
                :max="10"
                :min="0"
                readonly
              />
            </FormItem>
            <FormItem label="涡轮转动惯量(kg*m^2)" prop="turbineInertia">
              <Input
                type="number"
                v-model.number="detail.turbineInertia"
                style="width:100%"
                :max="10"
                :min="0"
                readonly
              />
            </FormItem>
            <FormItem label="油液密度(kg/m^3)" prop="oilDensity">
              <Input
                type="number"
                v-model.number="detail.oilDensity"
                style="width:100%"
                :max="1000"
                :min="0"
                readonly
              />
            </FormItem>
            <FormItem label="重量(kg)" prop="weight">
              <Input
                type="number"
                v-model.number="detail.weight"
                style="width:100%"
                :max="3000"
                :min="0"
                readonly
              />
            </FormItem>
            <FormItem :label-width="30">
              其他人是否可见
              <i-switch
                v-model="detail.isIndexShow"
                :true-value="1"
                :false-value="0"
                disabled
              />
              其他人是否可用
              <i-switch
                v-model="detail.otherCanUse"
                :true-value="1"
                :false-value="0"
                disabled
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>

    <Collapse v-model="collapseData">
      <Panel name="1">
        Cf曲线
        <div slot="content">
          <Row style="align-items: flex-start;margin-bottom:5px;display:block">
            <Col :lg="10" :xs="22" offset="0.5">
              <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
                <template #buttons>
                  <vxe-button size="mini" status="primary" @click="impotEvent"
                  >导入</vxe-button
                  >
                  <vxe-button size="mini" status="primary" @click="exportFile"
                  >导出</vxe-button
                  >
                  <vxe-button size="mini" status="primary" @click="addRow"
                  >新增</vxe-button
                  >
                  <vxe-button size="mini" status="danger" @click="delRow"
                  >删除</vxe-button
                  >
                  <vxe-button size="mini" @click="saveData">保存</vxe-button>
                </template>
              </vxe-toolbar>
              <vxe-table
                ref="xTable"
                height="400"
                border
                highlight-hover-row
                show-overflow
                :edit-rules="validRules"
                class="sortable-row-demo"
                :data="tablePage.listPage"
                :print-config="{}"
                :export-config="{
            filename: filename(),
            columnFilterMethod: filterExport1,
            type: 'cvs'
          }"
                :loading="loading"
                :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate }"
              >
                <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
                <vxe-column v-if="isUpdate" width="60">
                  <template #default>
              <span class="drag-btn">
                <i class="vxe-icon--menu"></i>
              </span>
                  </template>
                  <template #header>
                    <vxe-tooltip
                      v-model="showHelpTip1"
                      content="按住后可以上下拖动排序！"
                      enterable
                    >
                      <i
                        class="vxe-icon--question"
                        @click="showHelpTip1 = !showHelpTip1"
                      ></i>
                    </vxe-tooltip>
                  </template>
                </vxe-column>
                <vxe-column
                  field="speedRatio"
                  title="速比"
                  :edit-render="{ name: 'input' }"
                ></vxe-column>
                <vxe-column
                  field="torqueRatio"
                  title="变矩比"
                  :edit-render="{ name: 'input' }"
                ></vxe-column>
                <vxe-column
                  field="capacity"
                  title="能容系数"
                  :edit-render="{ name: 'input' }"
                ></vxe-column>
                <vxe-column
                  field="efficiency"
                  title="效率%"
                  :edit-render="{ name: 'input' }"
                ></vxe-column>
              </vxe-table>

              <vxe-pager
                :current-page="tablePage.currentPage"
                :page-size="tablePage.pageSize"
                :total="tablePage.totalResult"
                :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total'
          ]"
                @page-change="handlePageChange"
              >
              </vxe-pager>
            </Col>
            <Col :lg="12" :xs="22" offset="0.5">
              <div style="height:440px;" id="a"></div>
            </Col>
          </Row>
        </div>
      </Panel>
    </Collapse>

  </div>
</template>

<script>
import { torqueConverterLambdaApi } from "@/api/torque-converter-lambda";
import Sortable from "sortablejs";
import XEUtils from "xe-utils";
import XLSX, { WorkSheet } from "xlsx";
const PAGE_SIZE_INIT = 20;
export default {
  name: "TorqueConverterLambda",
  components: {},
  props: {},
  data() {
    return {
      collapseData: ["1"],
      loading: false,
      validRules: {
        speedRatio: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        torqueRatio: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        capacity: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        efficiency: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      },
      sortable1: null,
      showHelpTip1: false,
      detail: {}, // 详情信息
      torqueConvertId: null,
      tableData: [], // 表格列表数据-- 总数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      },
      // 表单验证
      formValidate: {
        // 编号
        sn: [{ required: true, message: "请输入编号", trigger: "change" }],
        // 型号
        model: [{ required: true, message: "请输入型号", trigger: "change" }],

        // 循环圆直径(mm)
        diameter: [
          {
            type: "number",
            required: true,
            message: "请输入循环圆直径(mm)",
            trigger: "change"
          },
          {
            type: "number",
            min: 0,
            max: 5000,
            message: "请输入0到5000的数字",
            trigger: "change"
          }
        ],
        // 启动变矩比
        initialTorqueRatio: [
          {
            type: "number",
            required: true,
            message: "请输入启动变矩比",
            trigger: "change"
          },
          {
            type: "number",
            min: 0,
            max: 100,
            message: "请输入0到100的数字",
            trigger: "change"
          }
        ],
        pumpInertia: [
          {
            type: "number",
            min: 0,
            max: 10,
            message: "请输入0到10的数字",
            trigger: "change"
          }
        ],
        turbineInertia: [
          {
            type: "number",
            min: 0,
            max: 10,
            message: "请输入0到10的数字",
            trigger: "change"
          }
        ],
        oilDensity: [
          {
            type: "number",
            min: 0,
            max: 1000,
            message: "请输入0到1000的数字",
            trigger: "change"
          }
        ],
        weight: [
          {
            type: "number",
            min: 0,
            max: 3000,
            message: "请输入0到3000的数字",
            trigger: "change"
          }
        ],
        // 特性类型
        type: [
          { required: true, message: "请输入特性类型", trigger: "change" }
        ],
        // 图片
        image: [{ required: true, message: "请上传图片", trigger: "change" }],
        isUpdate: false
      }
    };
  },
  computed: {},
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {
    // 启动列名拖动
    this.columnDrop2();
  },
  mounted() {
    this.torqueConvertId = this.$route.query.id;
    // 获取表单详情数据
    this.getById();
    // 初始化数据
    this.initData();

    this.rowDrop();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    filename() {
      return (
        "变矩器曲线" +
        new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", "")
          .replaceAll("-", "")
          .replaceAll(":", "")
      );
    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },

    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      this.torqueConvertId = this.$route.query.id;
      // 初始化数据
      this.initData();
    },
    columnDrop2() {
      this.$nextTick(() => {
        const $table = this.$refs.xTable;
        this.sortable2 = Sortable.create(
          $table.$el.querySelector(
            ".body--wrapper>.vxe-table--header .vxe-header--row"
          ),
          {
            handle: ".vxe-header--column:not(.col--fixed)",
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn();
              const targetThElem = item;
              const wrapperElem = targetThElem.parentNode;
              const newColumn = fullColumn[newIndex];
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(
                    targetThElem,
                    wrapperElem.children[oldIndex]
                  );
                } else {
                  wrapperElem.insertBefore(
                    wrapperElem.children[oldIndex],
                    targetThElem
                  );
                }
                return this.$XModal.message({
                  content: "固定列不允许拖动！",
                  status: "error"
                });
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(
                tableColumn[oldIndex]
              );
              const newColumnIndex = $table.getColumnIndex(
                tableColumn[newIndex]
              );
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
              fullColumn.splice(newColumnIndex, 0, currRow);
              $table.loadColumn(fullColumn);
            }
          }
        );
      });
    },
    getById() {
      torqueConverterLambdaApi.getById(this.torqueConvertId).then(res => {
        if (res.data) {
          this.detail = res.data;
          this.detail.createUser == this.$store.state.user.userLoginInfo.id
            ? (this.isUpdate = true)
            : (this.isUpdate = false);
        }
      });
    },

    // 行数据移动
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },

    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          debugger;
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            console.log("解析的输入：");
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["speedRatio"] = val;
                  } else if (cIndex == 1) {
                    item["torqueRatio"] = val;
                  } else if (cIndex == 2) {
                    item["capacity"] = val;
                  } else if (cIndex == 3) {
                    item["efficiency"] = val;
                  }

                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },
    exportExcel1() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "变矩器曲线.xlsx");
    },
    /**
     * @desc 渲染echart
     * @sicne 2021/11/13
     */
    renderEchart() {
      /* // 速比
            const speedRatio = this.tableData.map(item=>item.speedRatio)
            // 变矩比
            const torqueRatio = this.tableData.map(item=>item.torqueRatio)
            // 能容系数
            const capacity = this.tableData.map(item=>item.capacity)
            // 效率
            const efficiency = this.tableData.map(item=>item.efficiency) */

      // 组合数据格式[x, y]
      // 变矩比
      const torqueRatio = [];
      const capacity = [];
      const efficiency = [];

      // 曲线回转问题处理
      let tempTableData = [...this.tableData];
      tempTableData.sort((a, b) => a.speedRatio - b.speedRatio); // 排序

      tempTableData.forEach(item => {
        const temp = [];
        temp.push(item.speedRatio);
        temp.push(item.torqueRatio);
        torqueRatio.push(temp);

        const tmep1 = [];
        tmep1.push(item.speedRatio);
        tmep1.push(item.capacity);
        capacity.push(tmep1);

        const tmep2 = [];
        tmep2.push(item.speedRatio);
        tmep2.push(item.efficiency);
        efficiency.push(tmep2);
      });

      const line_map = { a: "变 矩 比", b: "能容系数", c: "效　率%" };

      const option = {
        title: {
          text: "Cf曲线"
        },
        tooltip: {
          trigger: "item",
          formatter: function(params) {
            console.log("-=-=-=>>>", params);
            let str = "";
            if (params) {
              const { seriesId } = params;
              str =
                str +
                line_map[seriesId] +
                "->[" +
                params.data[0] +
                ", " +
                params.data[1] +
                "]";
              str += "</br>";
            } else {
              return "";
            }

            return str;
          }
        },
        legend: {
          x: "right",
          data: ["变矩比", "能容系数", "效率%"],
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "20%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "速比",
          nameLocation: "center",
          axisLine: { onZero: false },
          nameGap: 20
        },
        yAxis: [
          {
            name: "效率",
            type: "value",
            position: "left",
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: "#248EFD"
              },
              show: true
            }
          },
          {
            name: "能容系数",
            axisLine: {
              lineStyle: {
                color: "#FD2446"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            },
            offset: 50
          },
          {
            name: "变矩比",
            axisLine: {
              lineStyle: {
                color: "#C916F2"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            },
            offset: 100
          }
        ],

        series: [
          {
            id: "a",
            name: "变矩比",
            type: "line",
            smooth: true,
            symbolSize: 5,
            data: torqueRatio,
            yAxisIndex: "2",
            itemStyle: {
              normal: {
                color: "#C916F2",
                lineStyle: {
                  color: "#C916F2"
                }
              }
            }
          },
          {
            id: "b",
            type: "line",
            name: "能容系数",
            smooth: true,
            symbolSize: 5,
            data: capacity,
            yAxisIndex: "1",
            itemStyle: {
              normal: {
                color: "#FD2446",
                lineStyle: {
                  color: "#FD2446"
                }
              }
            }
          },
          {
            id: "c",
            name: "效率%",
            type: "line",
            smooth: true,
            symbolSize: 10,
            data: efficiency,
            yAxisIndex: "0",
            itemStyle: {
              normal: {
                color: "#248EFD",
                lineStyle: {
                  color: "#248EFD"
                }
              }
            }
          }
        ]
      };
      let myChart = this.echarts.init(document.getElementById("a"));
      myChart.clear();
      myChart.setOption(option);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        efficiency: null,
        capacity: null,
        torqueRatio: null,
        speedRatio: null,
        index: new Date().getTime()
      };
      this.tableData.push(record);
      this.findList();
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "efficiency");
      this.reRenderTable();
    },
    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }
      // 速比
      const speedRatio = this.tableData.map(item => item.speedRatio);
      // 变矩比
      const torqueRatio = this.tableData.map(item => item.torqueRatio);
      // 能容系数
      const capacity = this.tableData.map(item => item.capacity);
      // 效率
      const efficiency = this.tableData.map(item => item.efficiency);

      const torqueConvertId = this.torqueConvertId;

      const param = {
        speedRatio: JSON.stringify(speedRatio),
        torqueRatio: JSON.stringify(torqueRatio),
        capacity: JSON.stringify(capacity),
        efficiency: JSON.stringify(efficiency),
        tableData: JSON.stringify(this.tableData),
        torqueConvertId: torqueConvertId
      };
      this.loading = true;
      torqueConverterLambdaApi
        .addTorqueConverterLambda(param)
        .then(res => {
          this.$Message.warning("保存成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      this.loading = true;
      torqueConverterLambdaApi
        .getByTorqueConvertId(this.torqueConvertId)
        .then(res => {
          console.log("---->>>", res);
          const data = res.data;
          if (data) {
            // 组合table数据
            const tableData = JSON.parse(data.tableData);
            if (tableData && tableData.length > 0) {
              this.tableData = tableData;
              this.findList();
            }
            this.renderEchart();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
<style>
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
<style>
#cont {
  background-color: #fff;
  padding: 30px 30px 0 30px;
}

.tb-row1 {
  border: 1px solid #eee;
}

.tb-row1 > div {
  border-right: 1px solid #eee;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  padding-left: 10px;
}

.tb-row1 > div:first-child {
  color: #666;
  background: #f5f5f5;
  text-align: center;
  font-weight: bold;
}

.tb-row1 > div:nth-child(3) {
  color: #666;
  background: #f5f5f5;
  text-align: left;
  font-weight: bold;
  text-align: center;
}

.tb-row1 > div:last-child {
  border-right: 0;
}

.form-ex {
  margin-bottom: 20px;
}

.form-ex > div {
  width: 100px;
  display: inline;
}

.tab-detail {
  margin-bottom: 50px;
}
.tab-detail input {
  background-color: #f4f4f4 !important;
}
.tab-detail span {
  color: #000 !important;
}
.tab-detail i {
  display: none !important;
}
.detail-image-box {
  width: 100%;
  margin-bottom: 10px;
  height: 230px;
  border: 1px dashed #dcdee2;
  text-align: center;
  background: #f4f4f4;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 10px;
}
</style>
